package com.example.jbmsuppliers.sinopec.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.jbmsuppliers.R;
import com.example.jbmsuppliers.sinopec.net.NetDeceVersion;
import com.example.jbmsuppliers.sinopec.orderaddress.AddressEditActivity;
import com.example.jbmsuppliers.sinopec.utlis.ExitAppUtlis;
import com.example.jbmsuppliers.sinopec.view.DialogLoading;
import com.example.permission.myjbm.config.Config;
import com.example.weather.myframe.PopupSelectImage;
import com.jbm.jbmsupplier.util.BusinessEntity;
import com.jbm.jbmsupplier.util.ICtrl;
import com.squareup.picasso.Picasso;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import static com.example.jbmsuppliers.R.id.header_right;

/**
 * Created by 家帮忙 on 2017/3/1.
 * 把新的功能调用的接口都写在NetDeceVersion类里调用
 */

public class MyRegistrMessage extends ActivityUse {
    @InjectView(R.id.header_title)
    TextView headerTitle;
    @InjectView(R.id.header_right)
    TextView headerRight;
    @InjectView(R.id.header_back)
    ImageView headerBack;
    @InjectView(R.id.strename)
    EditText strename;
    @InjectView(R.id.streaddress)
    TextView streaddress;
    @InjectView(R.id.strefs)
    EditText strefs;
    @InjectView(R.id.strefw)
    EditText strefw;
    @InjectView(R.id.imagetupian)
    ImageView imagetupian;
    @InjectView(R.id.butt_tijiao)
    Button buttTijiao;

    private File file;
    private final int REGISBUIN = 0001;
    private BusinessEntity businessEntity22;
    private BusinessEntity business;
    private int state;
    private DialogLoading loader;

    @Override
    protected int setContentView1() {
        return R.layout.lz_register;
    }

    @Override
    protected void initView() {
        ExitAppUtlis.getInstance().addActivity(this);
        ButterKnife.inject(this);
        initViews();
    }


    //戴舒予写
    private void initViews() {
        loader=new DialogLoading(this);
        //代表服务器调回  未合格
        businessEntity22 = (BusinessEntity) getIntent().getSerializableExtra("businessEntity");

        //审核状态      0是审核中   2是退回
        state = getIntent().getIntExtra("state", 1);
        switch (state) {
            case 0:
                headerTitle.setText("审核中");
                headerRight.setVisibility(View.GONE);
                buttTijiao.setVisibility(View.GONE);
                strename.setText(businessEntity22.getBusName());
                strefs.setText(businessEntity22.getBusAddr());
                strefw.setText(businessEntity22.getSellscope());
                streaddress.setText(businessEntity22.getBusAddr());
                Picasso.with(this).load(Config.PHOTOPATH + businessEntity22.getmFilepath()).into(imagetupian);


                strename.setEnabled(false);
                strefs.setEnabled(false);
                strefw.setEnabled(false);
                streaddress.setEnabled(false);


                break;
            case 2:
                headerTitle.setText("修改商家");
                headerRight.setText("修改");
                if (businessEntity22 != null) {
                    hint(businessEntity22.getAuditLogEntity().getRefuseinfo());//填写理由
                    strename.setText(businessEntity22.getBusName());
                    strefs.setText(businessEntity22.getBusAddr());
                    strefw.setText(businessEntity22.getSellscope());
                    streaddress.setText(businessEntity22.getBusAddr());
                    Picasso.with(this).load(Config.PHOTOPATH + businessEntity22.getmFilepath()).into(imagetupian);

                }
                break;
            default:
                headerTitle.setText("注册商家");
                headerRight.setText("申请");
                break;
        }


    }

    /*
         * 以当前时间命名照片
         * */


    private boolean result;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;


        if (requestCode == 200) {
            result = true;

            file = (File) data.getSerializableExtra("file");
            Picasso.with(MyRegistrMessage.this).load(file).into(imagetupian);
//            picture = new File(file, photoName);
//            BitmapFactory.Options opts = new BitmapFactory.Options();
//            opts.inSampleSize = 4;
//            bitmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), opts);
//            try {
//                FileOutputStream os = new FileOutputStream(picture);
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 85, os);
//                imagetupian.setVisibility(View.VISIBLE);
//                imagetupian.setImageBitmap(bitmap);
//                os.close();
//            } catch (Exception e) {
//                Log.e("main", Log.getStackTraceString(e));
//            }

        }
        if (requestCode == 900) {
            if (!data.getStringExtra("address").equals("")) {
                streaddress.setText(data.getStringExtra("address"));
            }
            ;


        }
    }

    @OnClick({R.id.header_right, R.id.header_back, R.id.streaddress,R.id.butt_tijiao})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.butt_tijiao:
//                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                file = new File(Environment.getExternalStorageDirectory() + "/MallImage");
//                photoName = getPhotoFileName();
//                if (!file.exists())
//                    file.mkdirs();
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(file, photoName)));
                Intent intent = new Intent(MyRegistrMessage.this, PopupSelectImage.class);
                startActivityForResult(intent, 200);
                break;
            case header_right:
                if (strename.getText().toString().equals("")) {
                    hint("商品名称不能为空");
                    return;
                } else if (streaddress.getText().toString().equals("")) {
                    hint("商品地址不能为空");
                    return;
                } else if (strefs.getText().toString().equals("")) {
                    hint("服务方式不能为空");
                    return;
                } else if (strefw.getText().toString().equals("")) {
                    hint("经营范围不能为空");
                    return;
                } else if (businessEntity22 == null) {
                    if (file == null) {
                        hint("请选择证件图片");
                        return;
                    }
                }
                //代表不是修改用户
                if (businessEntity22 == null) {
                    business = new BusinessEntity();
                    business.setBusName(strename.getText().toString());
                    business.setBusAddr(streaddress.getText().toString());
                    business.setServicestyle(strefs.getText().toString());
                    business.setSellscope(strefw.getText().toString());
                    business.setmFilepath(file.getName());
                    business.setPicByte(getFileToByte(file));
                }
                //代表是修改商家  并且没有重新上传图片

//                    ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
//                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);//把bitmap100%高质量压缩 到 output对象里
//                    bitmap.recycle();//自由选择是否进行回收
//                    byte[] result = output.toByteArray();//转换成功了
                NetDeceVersion nerdece = new NetDeceVersion(handler);

                //代表是修改商家信息
                if (businessEntity22 != null) {
                    //
                    if (businessEntity22 != null && result == false) {
                        nerdece.setUpdateBusiness(businessEntity22.getBusId(), strename.getText().toString(), streaddress.getText().toString(), strefs.getText().toString(), strefw.getText().toString(), businessEntity22.getmFilepath(), null, 0);
                    } else {
                        nerdece.setUpdateBusiness(businessEntity22.getBusId(), strename.getText().toString(), streaddress.getText().toString(), strefs.getText().toString(), strefw.getText().toString(), file.getName(), getFileToByte(file), 0);
                    }
                } else {

                    nerdece.setRegisBusin(business, REGISBUIN);
                }
            loader.show();
                loader.setTextstr("请稍等...");
                break;
            case R.id.header_back:
                finish();
                break;
            case R.id.streaddress: {
                Intent add = new Intent(this, AddressEditActivity.class);
                add.putExtra("add", "add");
                startActivityForResult(add, 900);
                break;
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ICtrl busin;
            switch (msg.what) {
                case REGISBUIN:
                    busin = (ICtrl) msg.obj;
                    if (busin.back) {
                        finish();
                    } else {
                        hint(busin.errorinfo);
                    }
                    break;
                case NetDeceVersion.UPCHANT:
                    busin = (ICtrl) msg.obj;
                    if (busin.back) {
                        finish();
                    } else {
                        hint(busin.errorinfo);
                    }
                    break;

            }
            super.handleMessage(msg);
            loader.dismiss();
        }
    };

    public byte[] getFileToByte(File file) {
        byte[] by = new byte[(int) file.length()];
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            by = bytestream.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return by;
    }

}
